# -*- coding: utf-8 -*-
"""Presenter for Add Words screen

gamestate.players must be Players
gamestate.players.players must be list of Players
gamestate.current_added_player must be Player
gamestate.current_added_player.name must be string
gamestate.current_added_player.words must be empty list or list of valid words
gamestate.settings.word_number must be int
"""
from kivy.uix.gridlayout import GridLayout
from kivy.properties import NumericProperty, StringProperty, ListProperty
from model.gamestate import Word, Phase, Hat
from model.dictionary import Dictionary
from ui.hat_widget import HatWidget, open_ok_popup
from kivy.clock import Clock


class AddWords(HatWidget):
    """Root widget

    """
    next_button_text = StringProperty()
    player_name = StringProperty()
    word_count = NumericProperty()
    cur_count = NumericProperty()

    def __init__(self, gamestate=None, presenter=None, **kwargs):
        """Constructor interface for MainView"""
        self.gamestate = gamestate
        self.presenter = presenter
        self.player = self.gamestate.current_added_player
        self.player_name = self.player.name
        self.word_count = self.gamestate.settings.words_number
        self.words = self.player.words
        self.cur_count = len(self.words)
        super(AddWords, self).__init__(**kwargs)
        self.word_list.bind(minimum_height=self.word_list.setter('height'))
        self.update_button_text()
        self.word_input.focus = True
        for word in self.words:
            self.word_list.draw_word(word.text)

        self.count_dicts()

    def count_dicts(self):
        dicts = self.presenter.settings.dictionaries.enabled_dictionaries
        for key in dicts:
            if dicts[key]:
                self.add_dict_but.enabled = True
                return
        self.add_dict_but.enabled = False

    def finish(self):
        """Finish entering words"""
        self.gamestate.current_added_player.finished_entering = True
        self.presenter.change_phase(Phase.JOIN if self.gamestate.is_joining
                                    else Phase.START_GAME)

    def from_dict(self):
        """Fill word list with words from dictionary"""
        count = self.word_count - self.cur_count
        dict_ = Dictionary.get_dict(None)
        deny_words = []
        for word in self.words:
            deny_words.append(word.text)
        l = dict_.get_words(count, deny_words)
        if len(l) != count:
            open_ok_popup(_(u'Error'), _(u'Dict is too small'), self)
        for word in l:
            self.word_list.add_word(word)
        self.set_buttons_state()
        self.update_button_text()

    def add_user_word(self, input_):
        """Add single word from user's input"""
        if len(self.words) == self.word_count:
            return
        self.word_list.on_add_word(input_)
        self.set_buttons_state()
        self.update_button_text()
        self.word_input.focus = True
        Clock.schedule_once(self.focus_on_word_input, 0)

    def focus_on_word_input(self, dt):
        self.word_input.focus = True

    def del_word(self, word):
        """"""
        self.word_list.del_word(word)
        self.set_buttons_state()
        self.update_button_text()

    def set_buttons_state(self):
        """Enables and disables buttons depending on words count"""
        if len(self.words) == self.word_count:
            self.add_word_but.enabled = False
            self.add_dict_but.enabled = False
        else:
            self.add_word_but.enabled = True
            self.add_dict_but.enabled = True

    def update_button_text(self):
        words_counter = str(len(self.words)) + '/' + \
            str(self.word_count)
        if len(self.words) < self.word_count * 0.4:
            self.next_button_text = words_counter
            self.next_butt.enabled = False
            self.next_butt.color_name = 'default'
        else:
            if len(self.words) < self.word_count:
                self.next_button_text = u'{} ({})'.format(_('Next'),
                                                          words_counter)
                self.next_butt.color_name = 'deem_green'
            else:
                self.next_button_text = _('Next')
                self.next_butt.color_name = 'green'
            self.next_butt.enabled = True

    def go_back(self):
        self.presenter.change_phase(Phase.ADD_PLAYER)

    def plus_butt_up(self, val):
        """
        WTF? unused method?
        """
        if val.strip() == '':
            self.add_word_but.enabled = False
        else:
            self.add_word_but.enabled = True


class ListElement(GridLayout):
    """Widget for element of list

    Consists of word label and deleting button
    """
    pass


class WordList(GridLayout):
    """Widget for word list

    Container under ScrollView
    """

    def on_add_word(self, input_):
        """Handle clicking on plus button

        Args:
        input_: (TextInput) input with word text
        """
        if input_.text.strip() != '':
            self.add_word(input_.text.strip())
            input_.text = ''

    def add_word(self, text):
        """Add word to list

        Args:
        text: (unicode) word text
        """
        if not text or self.parent.cur_count >= self.parent.word_count:
            return
        self.parent.words.append(Word(self.parent.player,
                                      text))
        self.draw_word(text)

    def draw_word(self, text):
        """Displays word in lists

        Args:
        text: (unicode) word text
        """
        self.parent.cur_count += 1
        el = ListElement()
        el.word = text
        self.add_widget(el)

    def del_word(self, word):
        """Delete word from list

        Args:
        word: (ListElement) representing word to be deleted
        """
        text = word.word
        for i in range(len(self.parent.words)):
            if self.parent.words[i].text == text:
                self.parent.words.pop(i)
                break
        self.remove_widget(word)
        self.parent.cur_count -= 1
